<template>
  <el-tree-select
    v-model="lableValue"
    :multiple="mergeConfigTreeSelect.multiple"
    :multiple-limit="mergeConfigTreeSelect.multiplelimit"
    :clearable="mergeConfigTreeSelect.clearable"
    :placeholder="mergeConfigTreeSelect.placeholder"
    :disabled="mergeConfigTreeSelect.disabled"
    :size="mergeConfigTreeSelect.size"
    :data="data"
    style="width: 240px"
  />
</template>

<script setup lang="ts">
  import { TreeSelectConfig } from '@/types/config'
  import { DictItem } from '@/types/dict'
  import { mergeConfig } from '@/utils/configMerge'
  import { computed, ref } from 'vue'
  const lableValue = ref<string | string[]>('') // 文本实际绑定的值
  defineOptions({ name: 'DictCatalogTree' })
  interface props {
    dictCode: string
    config?: Partial<TreeSelectConfig>
    value?: string | string[] // 支持单选和多选
  }
  const emit = defineEmits(['update:value'])
  const handleChange = (val: string | string[]) => {
    emit('update:value', val)
  }
  const props = withDefaults(defineProps<props>(), {
    dictCode: '',
    config: () => ({}),
  })
  const defaultConfig: TreeSelectConfig = {
    placeholder: '请选择',
    disabled: false,
    size: 'default',
    multiple: false,
    multiplelimit: 0,
    clearable: true,
  }
  const mergeConfigTreeSelect = computed(() => {
    return mergeConfig(defaultConfig, props.config)
  })
  // 树形数据
  const options = ref<DictItem[]>([])
  // 计算返回的数据类型和是否是树形结构
  const data = computed(() => {
    return dataType.value ? options.value : []
  })
  const dataType = computed(() => {
    return options.value.some((item) => item.children !== undefined)
  })
  // 构造树形数据
  const switchTree = () => {
    return cleanChildren(this.buildTree(this.options, '0'))
  }
  // 清理children属性
  const cleanChildren = (data: any) => {
    const fa = (list) => {
      list.map((e) => {
        if (e.children.length) {
          fa(e.children)
        } else {
          delete e.children
        }
        return e
      })
      return list
    }
    return fa(data)
  }
</script>

<style scoped>
  :deep(.el-tree-select) {
    width: 100%;
  }

  :deep(.el-tree-select__popper) {
    max-height: 350px;
  }

  :deep(.el-tree) {
    max-height: 300px;
    overflow-y: auto;
  }

  :deep(.el-tree::-webkit-scrollbar) {
    width: 6px;
  }

  :deep(.el-tree::-webkit-scrollbar-track) {
    background: #fff;
  }

  :deep(.el-tree::-webkit-scrollbar-thumb) {
    border-radius: 5px;
    background: #b4bccc;
  }
</style>
